package com.android.volley.http;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

public class FileBody extends BinaryBody {
    private final File mFile;

    public FileBody(File file) {
        super(file.getName(), new byte[0]);
        this.mFile = Objects.requireNonNull(file);
    }

    @Override
    public void writwTo(OutputStream out) throws IOException {
        InputStream fin = null;
        if(!mFile.exists()){
            throw new IOException("file not exists, " + mFile.getAbsolutePath());
        }
        try {
            fin = new FileInputStream(mFile);
            final byte[] tmp = new byte[4096];
            int len = 0;
            while ((len = fin.read(tmp)) != -1) {
                out.write(tmp, 0, len);
            }
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            closeSilently(fin);
        }
    }

    private void closeSilently(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}
